/*
 * Copyright (c) 2020, Peter Abeles. All Rights Reserved.
 *
 * This file is part of BoofCV (http://boofcv.org).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package boofcv.ohos;

import boofcv.alg.color.ColorFormat;
import boofcv.core.encoding.ConvertYuv420_888;
import boofcv.struct.image.ImageBase;
import ohos.media.image.Image;
import ohos.media.image.common.ImageFormat;
import org.ddogleg.struct.DogArray_I8;
import pabeles.concurrency.GrowArray;

import java.nio.ByteBuffer;

/**
 * Converts the ohos {@link Image} into a boofcv format.
 *
 * @author:Peter Abeles
 * @since 2021-05-11
 */
public class ConvertCameraImage {
    public static void imageToBoof(Image yuv, int width, int height, ColorFormat colorOutput, ImageBase output,
                                   GrowArray<DogArray_I8> workArrays) {
        if (BOverrideConvertOhos.invokeYuv420ToBoof(yuv, colorOutput, output))
            return;

        if (ImageFormat.YUV420_888 != yuv.getFormat())
            throw new RuntimeException("Unexpected format");

        Image.Component planesY = yuv.getComponent(ImageFormat.ComponentType.YUV_Y);
        Image.Component planesU = yuv.getComponent(ImageFormat.ComponentType.YUV_U);
        Image.Component planesV = yuv.getComponent(ImageFormat.ComponentType.YUV_V);

        ByteBuffer bufferY = planesY.getBuffer();
        ByteBuffer bufferU = planesU.getBuffer();
        ByteBuffer bufferV = planesV.getBuffer();

        int strideY = planesY.rowStride;
        int strideUV = planesV.rowStride;
        int stridePixelUV = planesV.pixelStride;

        ConvertYuv420_888.yuvToBoof(
                bufferY, bufferU, bufferV,
                width, height, strideY, strideUV, stridePixelUV,
                colorOutput, output, workArrays);
    }
}
